const ApiRes = require('../lib/utils/api-res')
const RoleService = require('../services/role')

// 创建角色
async function createRole(ctx) {
  const result = await RoleService.create(ctx.state.compiled, ctx.state.user.id)
  ctx.body = ApiRes.success(result)
}

// 查询所有角色
async function findAllRole(ctx) {
  const { current, size, code, name, status } = ctx.state.compiled

  const result = await RoleService.findPage(current, size, null, (original) => {
    let query = original

    if (name) {
      query = query.where('name', 'ilike', `%${name}%`)
    }

    if (code) {
      query = query.where('code', 'ilike', `%${code}%`)
    }

    if (status) {
      query = query.where('status', status)
    }

    return query
  })
  ctx.body = ApiRes.success(result)
}

// 查询单个角色
async function findRoleById(ctx) {
  const { id } = ctx.params
  const result = await RoleService.findOne(id)
  if (result) {
    ctx.body = ApiRes.success(result)
  } else {
    ctx.body = ApiRes.error(404, '角色不存在')
  }
}

// 删除角色
async function deleteRole(ctx) {
  const { id } = ctx.params
  const result = await RoleService.remove(id)
  if (result) {
    ctx.body = ApiRes.success(result)
  } else {
    ctx.body = ApiRes.error(404, '角色不存在')
  }
}

// 更新角色
async function updateRole(ctx) {
  const { id } = ctx.params
  const { body } = ctx.request

  const result = await RoleService.update(id, body)
  if (result?.length) {
    ctx.body = ApiRes.success(result)
  } else {
    ctx.body = ApiRes.error(404, '角色不存在')
  }
}

module.exports = {
  createRole,
  findAllRole,
  findRoleById,
  deleteRole,
  updateRole
}
